#include "e2d/core/render/CameraView.h"
#include "e2d/core/render/CameraViewEdit.h"
#include "e2d/core/trans/TransformNode.h"
#include "e2d/core/Entity.h"

void e2d::CameraView::OnLoad()
{

	int m_Width = m_ProjData.m_OrthographicWidth;
	int m_Height = m_ProjData.m_OrthographicHeight;

	fxcc::graph::common::RenderTargetJack::Desc desc(1, m_Width, m_Height, m_NrComponent, m_HDR);
	m_RenderTarget = e2d::GraphImpl::CreateRT(desc);
}


void e2d::CameraView::BeginRTT() const
{
	m_RenderTarget->Begin();
	m_RenderTarget->ClearColor(m_BackgroundColor);
	m_RenderTarget->ClearBuffer(m_ClearColor, m_ClearDepthStencil);
}

void e2d::CameraView::EndRTT() const
{
	m_RenderTarget->End();

}



void e2d::CameraView::CopySource()
{
	if (!m_SourceCamera.m_Entity)
	{
		return;
	}
	auto& m_transformNode = m_Entity->Get<e2d::TransformNode>();
	const auto& sourceTransformNode = m_SourceCamera.m_Entity->GetConst<e2d::TransformNode>();
	e2d::CameraView sourceCameraView;
	if (m_SourceCamera.m_Entity->HasComponent<e2d::CameraView>())
	{
		sourceCameraView = m_SourceCamera.m_Entity->GetConst<e2d::CameraView>();
		this->m_ProjData = sourceCameraView.m_ProjData;

	}
	else if (m_SourceCamera.m_Entity->HasComponent<e2d::CameraViewEdit>())
	{
		sourceCameraView = m_SourceCamera.m_Entity->GetConst<e2d::CameraViewEdit>();
		this->m_ProjData = sourceCameraView.m_ProjData;
	}
	else
	{
		ztclog::info("source camera do not have the camera or edit camera Object");
		return;
	}

	m_transformNode.SetWorldMatrix(sourceTransformNode.m_World.GetWorld());


}

void e2d::CameraView::UpdatePassData(e2d::Effect3d::PassData& passData)
{
	auto& transformNode = m_Entity->Get<e2d::TransformNode>();

	passData.m_Proj = GetProjMatrix();
	passData.m_View = transformNode.m_World.GetViewMatrix();
	passData.m_ProjView = passData.m_Proj * passData.m_View;
	passData.m_SkyboxView = transformNode.m_World.GetViewMatrixNoTranslation();
	passData.m_ViewPos = transformNode.m_World.m_Position;
	passData.m_NearZ = m_ProjData.m_ClipPlaneNear;
	passData.m_FarZ = m_ProjData.m_ClipPlaneFar;;
}
;

glm::mat4 e2d::CameraView::GetProjMatrix() const
{

	return m_ProjData.GetProjMatrix();
}



std::shared_ptr<e2d::Texture2DJack> e2d::CameraView::GetTextureEditing() const
{
	return m_RenderTarget->GetTexture(m_EditingIndex);
}